<?php

namespace app\admin\middleware;

use app\Request;
use think\Config;
use think\exception\HttpException;
use Xin\Auth\UserInterface;

class CheckAuth{

	/**
	 * @var \app\Request
	 */
	private $request;

	/**
	 * @var \think\Config
	 */
	private $config;

	/**
	 * @var \Xin\Auth\UserInterface
	 */
	private $user;

	/**
	 * CheckAuth constructor.
	 *
	 * @param \app\Request            $request
	 * @param \think\Config           $config
	 * @param \Xin\Auth\UserInterface $user
	 */
	public function __construct(Request $request, Config $config, UserInterface $user){
		$this->request = $request;
		$this->config = $config;
		$this->user = $user;
	}

	/**
	 * @param \app\Request $request
	 * @param \Closure     $next
	 * @return mixed
	 */
	public function handle($request, \Closure $next){
		$controller = $request->controller(true);
		$action = $request->action();

		$rule = "{$controller}/{$action}";
		if(!$this->checkAuth($rule)){
			throw new HttpException(403, '禁止访问！');
		}

		return $next($request);
	}

	/**
	 * 校验权限
	 *
	 * @param string $rule
	 * @return bool
	 */
	private function checkAuth(string $rule){
		if($rule == "login/login"){
			return true;
		}

		$this->user->getUserInfo();

		return true;
	}
}
